<!--
    参数 ：
    access          String  访问方式：值=>code:使用唯一编码访问；值=>group:使用大类访问 初始化必须
    codes           String  多个使用","连接
    groups          String  多个使用","连接
    busiNo          String
    belongNo        String
    isInit          Boolean   初始化请求 必需
-->

<style scoped lang="less">
@import "./imagePreview.less";
</style>
<template>
    <div class="Preview">
        <div class="imgPreview">
            <div class="magnify-content">
                <div class="magnify-img overflow">
                    <div class="preview_img">
                        <div class="file-box">
                            <div class="img" v-if="showType==='img'">
                                <img
                                    :src="previewFile.imgSrc"
                                    ref="previewImg"
                                    @mousewheel="rollImg($event)"
                                    @mousedown="onImgStart"
                                    @mouseup="onImgStop"
                                    @mousemove="onImgMove"
                                    :style="imgStyle"
                                    alt
                                />
                            </div>
                            <div class="pdf" v-if="showType==='pdf'">
                                <embed ref="pdfPreview" :src="previewFile.imgSrc" width="100%" height="100%" type="application/pdf" />
                            </div>
                            <div class="video" v-if="showType==='video'">
                                <video controls>
                                    <source :src="previewFile.imgSrc" type="video/mp4" />
                                    <p>Sorry, your browser doesn't support embedded videos.</p>
                                </video>
                            </div>
                        </div>
                        <div class="magnify-footer">
                            <div class="magnify-toolbar">
                                <!-- <Button class="magnify-btn-prev" type="primary" size="small" @click="downPic" v-if="showType=='img'">下载</Button> -->
                                <Button class="magnify-btn-prev" type="primary" size="small" @click="prevPic">上一张</Button>
                                <Button class="magnify-btn-next" type="primary" size="small" @click="nextPic">下一张</Button>
                                <Button class="magnify-btn-rotateLeft" type="primary" size="small" @click="leftRotate" v-if="showType=='img'">左旋</Button>
                                <Button class="magnify-btn-rotateRight" type="primary" size="small" @click="rightRotate" v-if="showType=='img'">右旋</Button>
                                <!-- <Button class="magnify-btn-actualSize" type="primary" size="small" @click="save" v-if="showType=='img'">保存</Button> -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <ul class="thum">
                <li v-for="(item,index) in fileList" :key="index" @click="selectThumImg($event,index,item.type)" :class="{'cur':curIndex==index}">
                    <img :src="item.thumSrc" />
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
import pdfImg from "_p/basic/assets/img/pdf.png";
import videoImg from "_p/basic/assets/img/video.jpg";
import { deepClone } from "@/libs/utils/ObjectClone";
import { getAllFileList,getFileByUniqueCode } from '_p/basic/api/image/image-audit';
import { getUri } from "@/libs/tools";

export default {
    props: {
        access:{
            type:String,
            require:true,
        },
        groups:{
            type: String,
            require: false,
        },
        codes:{
            type: String,
            require: false,
        },
        busiNo:{
            type: String,
            require: false,
        },
        belongNo:{
            type: String,
            require: false,
        },
        isInit: {
            type: Boolean,
            default: false,
            require: true,
        },
        //接口查询使用，同系统不同服务使用
        path: {
            type: String,
            require: true,
        }
    },
    data() {
        return {
            imgStyle: {},
            historyVersion: 0,
            imgServiceNo: "TianHeCenter",
            fileList: [],
            imgModel: false,
            previewFile: "",
            previewPdfSrc: "",
            showType: "",
            curIndex: 0,
            totalIndex: 0,
            tempStyle: [],
        }
    },

    watch: {
        isInit: {
            immediate: true,
            handler: function (val) {
                console.log('isInit(val)', val);
                if (val) {
                    this.init()
                }else{
                    this.fileList=[]
                    this.tempStyle=[]
                    this.previewFile=""
                    this.previewPdfSrc=""
                    this.showType=""
                }
            }
        }
    },
    created() {
    },
    mounted() {
    },
    methods: {
        init() {
            if(this.access!="code"&&this.access!="group"){
                this.$Message.fail("请传入正确的初始化参数");
            }else{
                this.getPreviewFileList()
            }
            console.log('00000000')
        },
        getPreviewFileList() {
            if(this.access=="code"){
                getFileByUniqueCode(this.codes,this.busiNo,this.belongNo,this.path).then(res => {
                    if (res.code === "0000" && res.data.length > 0) {
                        this.sortData(res.data);
                    } else {

                    }
                }).catch(e => {
                })
            }

            if(this.access=="group"){
                let initParam = { busiNo:this.busiNo, belongNo:this.belongNo, busiNodes:this.groups, imgServiceNo: this.imgServiceNo, historyVersion: this.historyVersion };
                getAllFileList(initParam, this.path).then(res => {
                    if (res.code === "0000" && res.data.length > 0) {
                        this.sortData(res.data);
                    } else {

                    }
                }).catch(e => {
                })
            }

        },
        // 整理
        sortData(data) {
            let newData = [], r = [], _index = 0, tempStyle = [];
            if (Array.isArray(data) && data.length > 0) {
                data.forEach(ele => {
                    const { attachmentCode, attachmentName, busiNode, userId, viewTime, fileList } = ele;

                    Array.isArray(fileList) && fileList.forEach(e => {
                        let d,
                            thumSrc,
                            fileType = this.getFileType(e),
                            imgSrc = `${_AFS_PROJECT_CONFIG.apiUri}/${getUri('image')}/upload/getBlob/${e.fileType}/${e.fileId}`;

                        if (fileType === "pdf") {
                            thumSrc = pdfImg
                        } else if (fileType === "video") {
                            thumSrc = videoImg
                        } else if (fileType === "img") {
                            thumSrc = imgSrc // TODO : 缩略图
                        }
                        d = Object.assign({}, e, { _index, attachmentCode, attachmentName, busiNode, userId, viewTime, imgSrc, thumSrc })

                        newData.push(d);

                        r.push({ deg: 0, scale: 1, isSave: false, });
                        _index++;
                    })
                });
                console.log('整理newData', newData);
                this.fileList = newData;
                this.totalIndex = newData.length - 1;
                this.showType = this.getFileType();
                this.setPreviewFile();
                for (let i = 0; i < newData.length; i++) {
                    let obj = {
                        deg: 0,
                        zoom: 100

                    }
                    tempStyle.push(obj)
                }
                this.tempStyle = tempStyle
            }
        },
        // 点击键盘时间切换上下张
        keyupevent() {
            let _this = this;
            document.onkeydown = function (event) {
                event.preventDefault();
                let keycode = event.keyCode;
                console.log(keycode, "keycode")
                if (keycode == 39 || keycode == 40) {
                    _this.nextPic();
                } else if (keycode == 37 || keycode == 38) {
                    _this.prevPic();
                }
            }
        },
        rollImg(event) {
            event.preventDefault();
            // 缩放图片
            this.zoomImg(event.wheelDelta)

        },
        selectThumImg(event, index, type) {
            this.curIndex = index;
            this.showType = this.getFileType();
            this.setPreviewFile(this.showType);
            // console.log(this.curIndex,"this.curIndex")
        },
        // 点击上一张
        prevPic() {
            if (this.curIndex == 0) {
                this.$Message.warning("已经是第一张了");
            } else {
                this.curIndex--;
                this.showType = this.getFileType();
                this.setPreviewFile(this.showType);
                this.resetPic();
            }
        },
        // 点击下一张
        nextPic() {
            if (this.curIndex == this.totalIndex) {
                // this.curIndex=0;
                this.$Message.warning("已经是最后一张了");
            } else {
                this.curIndex++;
                this.showType = this.getFileType()
                this.setPreviewFile(this.showType)
                this.resetPic();
            }

        },
        // 重置样式
        resetPic() {
            this.tempStyle[this.curIndex].deg = 0;
            this.tempStyle[this.curIndex].zoom = 100;
            this.setStyle();
        },
        //左旋转
        leftRotate() {
            this.tempStyle[this.curIndex].deg -= 90;
            this.setStyle();
        },
        // 右旋转
        rightRotate() {
            this.tempStyle[this.curIndex].deg += 90;
            this.setStyle();
        },
        // 放大
        zoomImg() {
            this.tempStyle[this.curIndex].zoom += event.wheelDelta / 12;
            // 最大放大屏幕
            if (this.tempStyle[this.curIndex].zoom >= 250) {
                this.tempStyle[this.curIndex].zoom = 250;
            }
            if (this.tempStyle[this.curIndex].zoom <= 40) {
                this.tempStyle[this.curIndex].zoom = 40;
            }
            this.setStyle();
        },
        // 设置图片样式
        setStyle() {
            if (this.showType == "img") {
                let _this = this;
                this.$nextTick(() => {
                    _this.$refs.previewImg.style.transform = "translate(-50%, -50%) rotate(" + this.tempStyle[this.curIndex].deg + "deg)";
                    _this.$refs.previewImg.style.zoom = this.tempStyle[this.curIndex].zoom + '%';
                })
            }
        },
        // 设置当前预览文件
        setPreviewFile(type) {
            if (!this.fileList.length) return;
            this.previewFile = deepClone(this.fileList[this.curIndex])

        },
        // 文件类型
        getFileType(e) {
            let file = e || this.fileList[this.curIndex],
                type = '';
            if (!file) return type;
            switch (file.fileType) {
                case "jpg":
                case "png":
                case "jpeg":
                    type = 'img';
                    break;
                case "pdf":
                    type = 'pdf';
                    break;
                default:
                    type = 'img';
            }
            return type;
        },
        // 取消图片预览弹窗
        cancel() {
            this.$emit("close-img-model", false)
        },
        save() {
        },
        // 下载图片
        downPic() {
            const a = document.createElement('a');
            a.href = this.previewFile;
            a.download = this.fileList[this.curIndex].fileName;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        },
        getFileList() {
            return this.fileList
        },
        onImgStart(e) {
            e.preventDefault();
            if (e.button == 0) {
                this.canDrag = true;
                this.disX = e.clientX - e.target.offsetLeft;
                this.disY = e.clientY - e.target.offsetTop;
            }
        },
        onImgMove(e) {
            if (this.canDrag) {
                let left = e.clientX - this.disX + 'px';
                let top = e.clientY - this.disY + 'px';
                this.imgStyle = Object.assign({}, this.imgStyle, { left, top })
            }
        },
        onImgStop() {
            this.canDrag = false;
        },
    }
}
</script>

<style>
</style>
